package com.wealth.trade.web.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.wealth.member.entity.Membership;
import com.wealth.member.service.IMembershipService;
import com.wealth.order.entity.OrderPlat;
import com.wealth.order.service.IOrderPlatService;
import com.wealth.payment.entity.PaymentAccount;
import com.wealth.payment.enums.PaymentTypeEnum;
import com.wealth.payment.service.IPaymentAccountService;
import com.wealth.platform.entity.SldConfig;
import com.wealth.platform.enums.SldConfigTypeEnum;
import com.wealth.platform.service.ISldConfigService;
import com.wealth.system.service.ShiroMember;
import com.wealth.system.web.controller.BaseController;
import com.wealth.wechat.entity.WechatConfig;
import com.wealth.wechat.service.WechatConfigService;
import com.wealth.wechat.service.WechatPayApi;
import com.wealth.wechat.util.XmlParser;

import iaas.utils.CommonUtil;
import iaas.utils.MatrixToImageWriter;

/** 
 *  微信扫码支付
 *  @author chan
 *  
 *  模式二
 *  https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_5
 */
@Controller
@RequestMapping("/pay")
public class WechatPayController extends BaseController{
	
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private WechatPayApi wechatPayApi;
	@Autowired
	private WechatConfigService wechatConfigService;
	@Autowired
	private ISldConfigService sldConfigService;
	@Autowired
	private IPaymentAccountService accountService;
	@Autowired
	private IOrderPlatService orderPlatService;
	@Autowired
	private IMembershipService membershipService;

	@RequestMapping(value="/{orderid}")
	public String payForm(@PathVariable Long orderid,HttpServletRequest request)throws Exception{
		OrderPlat orderPlat = orderPlatService.get(orderid);
		orderPlat.setPaymentType(PaymentTypeEnum.WECHAT.getValue());
		orderPlatService.save(orderPlat);
		request.setAttribute("orderPlat", orderPlat);
		request.setAttribute("order", "active");
		return "wechatpay/pay";
	}
	
	/**
	 *（2）用户确认支付后调用微信支付【统一下单API】生成预支付交易；
     *（3）微信支付系统收到请求后生成预支付交易单，并返回交易会话的二维码链接code_url。
     *（4）商户后台系统根据返回的code_url生成二维码。
	 * create by chan on 2016-10-10
	 */
	@RequestMapping(value="/qrcode/{orderid}")
	public void qrcode(HttpServletRequest request,HttpServletResponse response,
			@PathVariable Long orderid,int height,int width) throws IOException{
		try {
			Long memberid = ShiroMember.getInstance().getMember().getId();
			
			/* ------------ 二维码链接 -------- */
			//会员身份
			Membership membership = membershipService.getMemberShipByMemberIdAndCorpId(memberid, corpid);
			String openid = membership.getOpenid();
			//企业微信信息
			WechatConfig wechatConfig = wechatConfigService.getWechatConfigByCorpid(corpid);
			//企业二级域名
			SldConfig sldConfig = sldConfigService.getSldConfigByCorpIdAndType(corpid, SldConfigTypeEnum.PC.getValue());
			//企业支付账户
			PaymentAccount account  = accountService.findByCorpIdAndPaymode(corpid, PaymentTypeEnum.WECHAT.getValue());
			//订单信息
			OrderPlat orderPlat = orderPlatService.get(orderid) ;
			//交易类型
			String tradeType = "NATIVE";
			//根据微信支付规定格式生成二维码
			JSONObject obj =  wechatPayApi.getPayParam(wechatConfig, sldConfig, account, tradeType, orderPlat, openid, request);
			String url  = obj.getString("code_url");
			
			/* ------------ 生成二维码 -------- */
			response.setHeader("Cache-Control", "no-catch");
			response.setContentType("image/jpeg");
			String format = "jpg";// 图像类型  
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();  
	        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); 
			BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height,hints);// 生成矩阵  
			MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream() );
		} catch (Exception e) {
		}
	}
	
	/** 
	 * 异步通知
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value="/notify_url/{orderid}",method=RequestMethod.POST)
	public void notify(Model model,@PathVariable Long orderid,HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		//wx支付结果通用通知
		System.out.println("=============================wx支付结果通用通知:..."+new Date());
	   	
	   	String notify_Xml = "<xml>"+
		"<return_code><![CDATA[%1$s]]></return_code>"+
		"<return_msg><![CDATA[%2$s]]></return_msg>"+
		"</xml>";
		   	
	   	String postStr = wechatPayApi.readStreamParameter(request.getInputStream());
	   	System.out.println("====wx支付结果通用通知参数postStr=:"+postStr);
	   	if(CommonUtil.isNotNull(postStr)){
		   	Map<String, Object> map_result = new HashMap<String, Object>();
		   	map_result=XmlParser.xmlStr2Map(postStr);
		   	
		   	if(CommonUtil.isNotNull(map_result.get("return_code"))){
			    String return_code = map_result.get("return_code").toString();
			    //String return_msg = map_result.get("return_msg").toString();
				
			    OrderPlat orderPlat = orderPlatService.get(orderid);
				if(return_code.equals("SUCCESS")){
					//wx支付 服务器回调 服务器订单 查询
					if(null!=orderPlat){
						//支付成功
						orderPlatService.payOrder(orderPlat);
					}
				}else{
					//wx支付 服务器回调 服务器订单 查询
					if(null!=orderPlat){
						//支付失败
						//order.setPaystatus(PayStatusEnum.FAIL.getValue());
						//orderService.saveAdoptionOrder(order);
					}
				}
		   	}
	   	}
//	   	return notify_Xml.format(notify_Xml, "SUCCESS","OK");
	   	
	   	System.out.println("=============================wx支付结果通用通知完成:..."+notify_Xml.format(notify_Xml, "SUCCESS","OK"));
	   	wechatPayApi.sendStream(response, notify_Xml.format(notify_Xml, "SUCCESS","OK"));
	}
}
